package io.stream.delete_zero;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * User: pavel
 * Date: 2/14/13
 * Time: 4:34 PM
 * To change this template use File | Settings | File Templates.
 */
public class DeleteZeroApp_lab {
    public static void main(String[] args) throws IOException {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream("/home/pavel/1.jpg");
            out = new FileOutputStream("/home/pavel/1_.jpg", false);

            long startTime = System.currentTimeMillis();
            while (true) {

                try {
                    int value = in.read();

                    if (value > 0) {
                        out.write(value);
                    } else if (value == -1) {
                        break;
                    }
                } catch (IOException e) {
                    System.out.println("Deleting file");
                    new File("/home/pavel/1_.jpg").delete();
                    throw new IOException("Read/Write error", e);
                }
            }
            long deltaTime = System.currentTimeMillis() - startTime;
            System.out.println(deltaTime);

        } catch (IOException e) {
            throw new IOException("Open file error", e);
        } finally {
            closeQuietly(in);
            closeQuietly(out);
        }
    }

    public static void closeQuietly(InputStream in) {
        System.out.println("Close in");
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                /*NOP*/
            }
        }

    }

    public static void closeQuietly(OutputStream out) {
        System.out.println("Close out");

        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                /*NOP*/
            }

        }

    }
}
